<template>
  <div>
    <el-form ref="ruleForm" v-loading="loading" :model="blog" label-width="100px">
      <el-form-item label="博客标题" prop="blogTitle">
        <el-input v-model="blog.blogTitle" />
      </el-form-item>
      <el-form-item label="封面地址" prop="blogImage">
        <el-input placeholder="可以不用填写" v-model="blog.blogImage" @blur="blurSetImage" />
      </el-form-item>
      <el-form-item label="封面" prop="blogImage">
        <!--      <el-input v-model="blog.blogImage" />-->
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" @error="imageError">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="分类名称" prop="typeName">
        <el-select v-model="blog.blogType" filterable clearable placeholder="请选择分类" style="width: 100%">
          <el-option
            v-for="item in typeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tagIds">
        <el-select v-model="tagIds" filterable multiple placeholder="请选择标签" style="width: 100%" @focus="getEnabledTags">
          <el-option
            v-for="item in tagList"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="博客内容" prop="typeName">
        <!--      <el-input v-model="blog.blogContent" />-->
        <mavon-editor
          ref="md"
          v-model="content"
          :ishljs="true"
          style="min-height: 400px"
          code-style="idea"
          @change="change"
          @imgAdd="imgAdd"
          @imgDel="imgDel"
        />
      </el-form-item>
      <el-form-item label="来源" prop="blogSource">
        <el-select v-model="blog.blogSource" filterable placeholder="请选择来源" style="width: 100%">
          <el-option
            :key="1"
            :label="'原创'"
            :value="'原创'"
          />
          <el-option
            :key="2"
            :label="'转载'"
            :value="'转载'"
          />
          <el-option
            :key="3"
            :label="'翻译'"
            :value="'翻译'"
          />
        </el-select>
        <!--<el-input v-model="blog.blogSource" />-->
      </el-form-item>
      <el-form-item label="博客简介" prop="blogRemark">
        <el-input v-model="blog.blogRemark" type="textarea" />
      </el-form-item>
      <el-form-item label="提交" label-width="100px">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" @click="submitFormAll">保存并提交</el-button>
        <el-button type="primary" @click="backBlog">回到博客界面</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
import blogApi from '../../../api/blog'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { getToken } from '@/utils/auth'
import tagApi from '../../../api/tag'
export default {
  name: 'BlogAdd',
  components: {
    mavonEditor
  },
  data() {
    return {
      blog: {
        blogTitle: '',
        blogImage: null,
        blogContent: '',
        blogType: 0,
        blogRemark: null,
        blogSource: '原创'
      },
      tagIds: [],
      tagList: [],
      headers: {
        Authorization: getToken()
      },
      typeList: this.$store.getters.typeList,
      imageUrl: '',
      uploadUrl: process.env.VUE_APP_UPLOAD_URL,
      loading: false,
      content: '', // 输入的markdown
      html: '', // 及时转的html
      imgFile: [],
      imgUrl: []
    }
  },
  created() {
    this.content = ''
  },
  methods: {
    imageError(e){
      this.blog.blogImage = null
      this.$message.error('图片加载失败')
    },
    blurSetImage() {
      this.imageUrl = this.blog.blogImage
    },
    /**
     * 添加图片事件
     */
    imgAdd(pos, $file) {
      const formdata = new FormData()
      formdata.append('file', $file)

      var that = this
      blogApi.uploadImg(formdata).then(res => {
        if (res.code === 200) {
          this.$message.success('上传成功')
          const url = res.data
          let name = $file.name
          that.imgFile[pos - 1] = {
            file: $file,
            url: url
          }
          if (name.includes('-')) {
            name = name.replace(/-/g, '')
          }
          const tent = that.content
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)  这里是必须要有的
          if (tent.includes(name)) {
            const oStr = `(${pos})`
            const nStr = `(${url})`
            const index = tent.indexOf(oStr)
            const str = tent.replace(oStr, '')
            const insertStr = (soure, start, newStr) => {
              return soure.slice(0, start) + newStr + soure.slice(start)
            }
            that.content = insertStr(str, index, nStr)
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 触发图片删除的东西
    imgDel(pos) {
      var formData = new FormData()
      const n = this.imgFile[pos[0] - 1]
      formData.append('url', n.url)
      const s = '![' + n.file.name + '](' + n.url + ')'
      const that = this
      blogApi.deleteImage(formData).then(res => {
        if (res.code === 200) {
          that.content.replace(s, '')
          that.imgFile.splice(pos[0] - 1, pos[0] - 1)
          that.$message.success('删除成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.html = render
    },
    handleUploadSuccess(res, file) {
      this.imageUrl = res.data
      this.blog.blogImage = res.data
    },
    getUploadUrl() {
      return process.env.VUE_APP_UPLOAD_URL
    },
    submitForm() {
      // this.blog.blogContent = this.html
      this.blog.tagIds = this.tagIds
      this.loading = true
      this.blog.blogContent = this.content
      console.log('博客内容', this.blog)
      if (this.blog.blogContent.trim() && this.blog.blogTitle.trim()) {
        blogApi.save(this.blog).then(res => {
          if (res.code === 200) {
            this.loading = false
            this.$message.success(res.msg)
            this.content = ''
            this.tagIds = []
            this.blog.blogContent = ''
            this.blog.blogImage = null
            this.blog.blogRemark = null
            this.blog.blogSource = ''
            this.blog.blogTitle = ''
            this.blog.blogType = ''
            this.$router.push('/Article/blog')
          } else {
            this.loading = false
          }
        }).catch(e => {
          console.error(e)
          this.loading = false
        })
      } else {
        this.loading = false
        this.$message.error('请输入内容和标题')
      }
    },
    /**
     * 保存并提交
     */
    submitFormAll() {
      // this.blog.blogContent = this.html
      this.blog.blogContent = this.content
      this.blog.tagIds = this.tagIds
      this.loading = true
      if (this.blog.blogContent && this.blog.blogContent.trim().length > 0 && this.blog.blogTitle.trim().length > 0) {
        blogApi.saveSubmit(this.blog).then(res => {
          if (res.code === 200) {
            this.loading = false
            this.$message.success(res.msg)
            this.content = ''
            this.tagIds = []
            this.blog.blogContent = ''
            this.blog.blogImage = null
            this.blog.blogRemark = null
            this.blog.blogSource = ''
            this.blog.blogTitle = ''
            this.blog.blogType = ''
            this.$router.push('/Article/blog')
          } else {
            this.loading = false
          }
        })
      } else {
        this.$message.error('请输入内容和标题')
        this.loading = false
      }
    },
    backBlog() {
      this.$router.push('/Article/blog')
    },
    getEnabledTags() {
      tagApi.getEnabledTags().then(res => {
        if (res.code === 200) {
          this.tagList = res.data
        }
      })
    }
  }
}
</script>

<style scoped>
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
